package com.xb.loan.encryptor.comm.protocol.impl;


import com.xb.loan.encryptor.bean.LotteryBean;
import com.xb.loan.encryptor.comm.protocol.Decoder;
import com.xb.loan.encryptor.util.LotteryBeanHelper;
import com.xb.loan.util.binaryConvert.BinaryParseUtil;
import com.xb.loan.util.binaryConvert.CryptUtil;
import com.xb.loan.util.binaryConvert.parse.ParsePointer;
import com.xb.loan.util.binaryConvert.parse.str.StringParser;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class DecoderImpl implements Decoder {
	
	private StringParser parser = new StringParser();

	@SuppressWarnings("unchecked")
	@Override
	public <T> T decode(InputStream in) throws IOException {
		
		DataInputStream dataInputStream = new DataInputStream(in);
		// 数据包长度字节
		int len = dataInputStream.readShort();
		// 数据包
		byte[] data = new byte[len];
		
		dataInputStream.readFully(data);
		// transcode
		ParsePointer pointer = new ParsePointer(2);
		
		String transcode = parser.convert(data, pointer, null, null);
		// 加密数据
		byte[] cryptData = Arrays.copyOfRange(data, pointer.getPointer(), data.length);
		
		byte[] realData = new byte[cryptData.length - 1];
		// 解密
		CryptUtil.decode(cryptData, realData, cryptData.length);
		// 解析对象
		LotteryBean response = BinaryParseUtil.convert(realData, LotteryBeanHelper.getTransCodeClass(transcode));
		
		return (T) response;
	}

}
